#include "mouse_input.hh"

MouseInput::MouseInput ()
  : is_released_ (false)
  , p_ray_ (0)
  , r_ray_ (0)
  , p2_cam_ (0)
  , r2_cam_ (0)
  , new_release_pos_ (false)
  , is_interface_ (false)
{}

MouseInput::~MouseInput ()
{
  if (p_ray_)
    delete p_ray_;

  if (r_ray_)
    delete r_ray_;

  if (p2_cam_)
    delete p2_cam_;

  if (r2_cam_)
    delete r2_cam_;
}

void
MouseInput::pressed (Camera* cam)
{
  int x = 0;
  int y = 0;

  SDL_GetMouseState (&x, &y);

  p_pos_ (0, x);
  p_pos_ (1, y);

  p_cam_ = cam->pos_get ();
  Vector2d cursor (p_pos_ (0) * 200 / Window::W_WIDTH - 100,
		   100 - p_pos_ (1) * 200 / Window::W_HEIGHT);
  if (p2_cam_)
    delete p2_cam_;
  p2_cam_ = (cam->get_3D_point (cursor (0), cursor (1)));

}

void
MouseInput::released (Camera* cam)
{
  int x = 0;
  int y = 0;

  SDL_GetMouseState (&x, &y);

  r_pos_ (0, x);
  r_pos_ (1, y);

  is_released_ = true;

  r_cam_ = cam->pos_get ();
  Vector2d cursor (r_pos_ (0) * 200 / Window::W_WIDTH - 100,
		   100 - r_pos_ (1) * 200 / Window::W_HEIGHT);
  if (r2_cam_)
    delete r2_cam_;
  r2_cam_ = (cam->get_3D_point (cursor (0), cursor (1)));
  new_release_pos_ = true;
}

void
MouseInput::catch_pos (Camera* cam)
{
  int x = 0;
  int y = 0;

  SDL_GetMouseState (&x, &y);

  r_pos_ (0, x);
  r_pos_ (1, y);

  r_cam_ = cam->pos_get ();
  Vector2d cursor (r_pos_ (0) * 200 / Window::W_WIDTH - 100,
		   100 - r_pos_ (1) * 200 / Window::W_HEIGHT);
  if (r2_cam_)
    delete r2_cam_;
  r2_cam_ = (cam->get_3D_point (cursor (0), cursor (1)));
  new_release_pos_ = true;
}

void
MouseInput::gen_press_ray ()
{
  if (!p_ray_)
    {
      p_ray_ = new Ray (p_cam_);
      p_ray_->set_line (*p2_cam_);
    }
}

void
MouseInput::gen_release_ray ()
{
  if (new_release_pos_ && r_ray_)
    {
      delete r_ray_;
      r_ray_ = 0;
    }

  if (!r_ray_)
    {
      r_ray_ = new Ray (r_cam_);
      r_ray_->set_line (*r2_cam_);
      new_release_pos_ = false;
    }
}
